package org.xurui.sxl.protocol.command.impl;

import lombok.extern.slf4j.Slf4j;
import org.jetlinks.core.message.CommonDeviceMessage;
import org.jetlinks.core.message.DeviceMessage;
import org.jetlinks.core.message.codec.EncodedMessage;
import org.jetlinks.core.message.codec.FromDeviceMessageContext;
import org.jetlinks.core.message.function.FunctionInvokeMessage;
import org.jetlinks.core.message.function.FunctionInvokeMessageReply;
import org.jetlinks.core.message.function.FunctionParameter;
import org.xurui.sxl.protocol.cache.ConcurrentMapCache;
import org.xurui.sxl.protocol.command.CmdCodec;
import org.xurui.sxl.protocol.enums.CommandEnum;
import org.xurui.sxl.protocol.utils.BinaryUtils;
import org.xurui.sxl.protocol.utils.NumberUtils;
import org.xurui.sxl.protocol.utils.SxlMessageUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 学生信息同步
 */
@Slf4j
public class CmdCodec_STUINFO implements CmdCodec {
    @Override
    public boolean supportsCmd(String cmd) {
        return CommandEnum.STUINFO.name().equals(cmd);
    }

    @Override
    public boolean supportsRelayCmd() {
        return true;
    }

    @Override
    public List<DeviceMessage> parsePayload(String payload, FromDeviceMessageContext context) {
        //设备回复格式：*XX,YYYYYYYYYYYYYYY,V4,STUINFO,seq,para,HHMMSS,S,latitude,D,longitude,G,speed,pdop,DDMMYY,tracker_status#
        //设备回复示例：*LX,2020916301,V4,STUINFO,173030,E5AE9EE9AA8CE4B880E5B08F,32303139E7BAA7E4B880E78FAD,E5AD99E6829FE7A9BA,www.baidu.com/icon.jpg,173031,A,2212.8745,N,11346.6574,E,14.28,2.8,220902,FFFFFFFF#
        FunctionInvokeMessageReply report = FunctionInvokeMessageReply.create();
        String[] payloadArr = payload.replaceAll("\\*","").split(",");
        String deviceId = payloadArr[1];
        report.setDeviceId(deviceId);
        Object messageIdObj = ConcurrentMapCache.getInstance().getAndRemove(deviceId+"_"+CommandEnum.STUINFO.name()+"_"+payloadArr[4]);
        String messageId = messageIdObj==null?null:messageIdObj.toString();
        if(messageId==null){
            messageId = deviceId+"_"+payloadArr[4];
        }

        report.setFunctionId(CommandEnum.STUINFO.name());
        report.setMessageId(messageId);
        report.setTimestamp(System.currentTimeMillis());
        String para=BinaryUtils.hexStr2Str(payloadArr[5])+","+BinaryUtils.hexStr2Str(payloadArr[6])+","+BinaryUtils.hexStr2Str(payloadArr[7])+","+payloadArr[8];

        Map<String, Object> properties = new HashMap<>();
        properties.put("para",para);
        properties.put("uptime",payloadArr[9]);
        properties.put("s",payloadArr[10]);
        properties.put("latitude",BinaryUtils.getWgs84LonLat(payloadArr[11],"lat"));
        properties.put("d",payloadArr[12]);
        properties.put("longitude",BinaryUtils.getWgs84LonLat(payloadArr[13],"lon"));
        properties.put("g",payloadArr[14]);
        properties.put("speed", NumberUtils.parseDouble(payloadArr[15]));
        properties.put("pdop",NumberUtils.parseDouble(payloadArr[16]));
        properties.put("upday", payloadArr[17]);
        String trackerStatusHex = payloadArr[18];


        Map<String,Object> trackerStatusMap = parseTrackerStatus(trackerStatusHex);
        properties.put("trackerstatus",trackerStatusMap);
        report.setOutput(properties);

        //TODO 更新状态
        return genDeviceMessage(report);
    }

    @Override
    public EncodedMessage encodeMessage(CommonDeviceMessage message,String zzs) {
        //平台下发消息
        //格式：*XX,YYYYYYYYYYYYYYY,STUINFO,HHMMSS,SCHOOLNAME,GRADE,STUNAME,HEADURL#
        //例子：*LX,2020916301,STUINFO,173030,E5AE9EE9AA8CE4B880E5B08F,32303139E7BAA7E4B880E78FAD,E5AD99E6829FE7A9BA,www.baidu.com/icon.jpg#
        //参数说明：SCHOOLNAME 学校名字；UTF-8 编码（16 进制内码）
        //参数说明： GRADE 年级班级；UTF-8 编码（16 进制内码）
        //参数说明： STUNAME 学生名字；UTF-8 编码（16 进制内码）
        //参数说明： HEADURL 头像 URL，http 链接地址，字符串中不应该出现*#,的字符
        if(message instanceof FunctionInvokeMessage) {
            FunctionInvokeMessage m = (FunctionInvokeMessage) message;
            List<FunctionParameter> params = m.getInputs();
            Map<String, Object> paramsMap = params.stream()
                .collect(Collectors.toMap(FunctionParameter::getName, FunctionParameter::getValue));
            String schoolName=paramsMap.get("schoolName").toString();
            String grade=paramsMap.get("grade").toString();
            String stuName=paramsMap.get("stuName").toString();
           /* if(paramsMap.get("schoolName")!=null && !paramsMap.get("schoolName").equals("")&& paramsMap.get("grade")!=null && !paramsMap.get("grade").equals("") && paramsMap.get("stuName")!=null && !paramsMap.get("stuName").equals("")) {*/
                String headUrl="";
                if(paramsMap.get("headUrl")!=null && !paramsMap.get("headUrl").equals("")){
                    if(BinaryUtils.isSpecialChar(paramsMap.get("headUrl").toString())){
                        log.error("该参数头像Url不能必填写[*#，]的特殊字符！");
                        return null;
                    }else {
                        headUrl=paramsMap.get("headUrl").toString();
                    }
                }

                String time = SxlMessageUtils.getTimeHHMMSS();//DateFormatUtils.format(new Date(),"HHmmss");
                /*StringBuffer sb = new StringBuffer();
                sb.append("*");
                sb.append(zzs);//TODO 需要修改成根据设备动态加载
                sb.append(",");
                sb.append(message.getDeviceId());
                sb.append(",");
                sb.append(CommandEnum.STUINFO.name());
                sb.append(",");
                sb.append(time);
                sb.append(",");
                sb.append(BinaryUtils.str2HexStr(schoolName));
                sb.append(",");
                sb.append(BinaryUtils.str2HexStr(grade));
                sb.append(",");
                sb.append(BinaryUtils.str2HexStr(stuName));
                sb.append(",");
                sb.append(headUrl);
                sb.append("#");*/
                ConcurrentMapCache.getInstance().set(message.getDeviceId()+"_"+CommandEnum.STUINFO.name()+"_"+time,message.getMessageId(),60*3*1000);
               // return EncodedMessage.simple(Unpooled.wrappedBuffer(sb.toString().getBytes()));


                return SxlMessageUtils.SxlCmd.getInstance()
                    .appendAndAddSeparator(zzs)
                    .appendAndAddSeparator(message.getDeviceId())
                    .appendAndAddSeparator(CommandEnum.STUINFO.name())
                    .appendAndAddSeparator(time)
                    .appendAndAddSeparator(BinaryUtils.str2HexStr(schoolName))
                    .appendAndAddSeparator(BinaryUtils.str2HexStr(grade))
                    .appendAndAddSeparator(BinaryUtils.str2HexStr(stuName))
                    .append(headUrl).buildEncodeMessage();
           /* }else{
                log.error("该参数学校名称，年级，学生名称不能为空必须填写！");
                return null;
            }*/


        }else{
            if (log.isDebugEnabled()) {
                log.debug("非FunctionInvokeMessage指令{}消息{}",CommandEnum.WIFISCAN.name(),message);
            }
            return null;
        }
    }


}
